package com.yyz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyz.domain.Employee;
import com.yyz.mapper.EmployeeMapper;
import com.yyz.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yyz
 * @create 2023-07-11 22:01
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 登录
     *
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Employee::getUsername, employee.getUsername());

        Employee emp = employeeMapper.selectOne(lqw);
        return emp;
    }

    /**
     * 添加员工a
     * @param emp
     */
    @Override
    public void insert(Employee emp) {
//        long id = (long) request.getSession().getAttribute("employee");

        emp.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));//初始化密码

//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
//        emp.setCreateUser(id);
//        emp.setUpdateUser(id);

        employeeMapper.insert(emp);
    }

    /**
     * 分页查询员工信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public IPage<Employee> pageList(Integer page, Integer pageSize, String name) {
        IPage<Employee> p = new Page<>(page, pageSize);

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);

        IPage<Employee> pageInfo = employeeMapper.selectPage(p, lqw);

        return pageInfo;
    }

    /**
     * 禁用
     *
     * @param request
     * @param emp
     */
    @Override
    public void forbidden(HttpServletRequest request, Employee emp) {
        Long id = (Long) request.getSession().getAttribute("employee");

        emp.setUpdateUser(id);

        employeeMapper.updateById(emp);
    }

    /**
     * 根据id页面回显
     * @param id
     * @return
     */
    @Override
    public Employee update(Long id) {
        Employee emp = employeeMapper.selectById(id);
        return emp;
    }
}
